﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using DM.DMTest.Tests;
using DM.Tests.Dtos;
using Microsoft.EntityFrameworkCore;

namespace DM.Tests
{
    public class TestAppService : DMAppServiceBase, ITestAppService
    {
        private readonly IRepository<Test> _testRepository;

        public TestAppService(IRepository<Test> testRepository)
        {
            this._testRepository = testRepository;
        }

        public async Task CreateOrUpdateTestAsync(CreateOrUpdateTestInput input)
        {
            if (input.TestEditDto.Id.HasValue)
            {
                //update
                await Update(input.TestEditDto);
            }
            else
            {
                //insert
                await Create(input.TestEditDto);
            }
        }

        private async Task Create(TestEditDto testEditDto)
        {
            await _testRepository.InsertAsync(testEditDto.MapTo<Test>());
        }

        private async Task Update(TestEditDto testEditDto)
        {
            var entity = await _testRepository.GetAsync(testEditDto.Id.Value);
            await _testRepository.UpdateAsync(testEditDto.MapTo(entity));
        }

        public async Task DeleteTestByIdAsync(EntityDto<int> inputDto)
        {
            await _testRepository.DeleteAsync(inputDto.Id);
        }

        public async Task<PagedResultDto<TestListDto>> GetPagedTestsAsync(GetTestInput input)
        {
            var query = _testRepository.GetAll();
            var testsCount = await query.CountAsync();
            var tests = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();
            var dtos = tests.MapTo<List<TestListDto>>();
            return new PagedResultDto<TestListDto>(testsCount, dtos);
        }

        public async Task<TestListDto> GetTestByIdAsync(NullableIdDto<int> input)
        {
            var entity = await _testRepository.GetAsync(input.Id.Value);
            return entity.MapTo<TestListDto>();
        }

        public async Task<GetTestForEditOutput> GetTestForEditAsync(NullableIdDto<int> input)
        {
            var result = new GetTestForEditOutput();

            if (input.Id.HasValue)
            {
                var entity = await _testRepository.GetAsync(input.Id.Value);
                var testEditDto = entity.MapTo<TestEditDto>();
                result.TestEditDto = testEditDto;
            }
            else
            {
                result.TestEditDto = new TestEditDto();
            }
            return result;
        }
    }
}
